// 上传 请求
import request from '@/utils/request'

import axios from "axios"
import {trace} from "../utils/trace"
import {getToken} from "../utils/auth"

// const __path = 'https://xinzhua.glpro.io:4009';
const __path = process.env.VUE_APP_BASE_API;    //'https://xinzhua.glpro.io:4009';

export function put1(url, data, onUploadProgress) {
  return request({
    url: url,
    method: 'post',
    data,
    headers: {
      "Content-Type": "multipart/form-data",
      "X-Requested-With": "XMLHttpRequest",
    },
    onUploadProgress: (progressEvent) => {
      let complete = (progressEvent.loaded / progressEvent.total).toFixed(2) | 0;
      if (onUploadProgress) {
        onUploadProgress(complete)
      }
    },

  })
}

export function put2(url, data, onUploadProgress) {
  axios.defaults.timeout = 30000;
  return axios({
    url: url,
    method: 'post',
    data,
    headers: {
      "Content-Type": "multipart/form-data",
      "X-Requested-With": "XMLHttpRequest",
    },
    onUploadProgress: (progressEvent) => {
      let complete = (progressEvent.loaded / progressEvent.total).toFixed(2) | 0;
      if (onUploadProgress) {
        onUploadProgress(complete)
      }
    },

  })
}

export function post(path, data, backfunc, time,method) {
  trace("post",data, time,method)
  var xmlHttp
  if (window.ActiveXObject) {
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

  } else if (window.XMLHttpRequest) {
    xmlHttp = new XMLHttpRequest();
  }

  xmlHttp.open(method||"put", __path+path, true);
  xmlHttp.timeout = time||3000;
  // xmlHttp.setRequestHeader("Content-type", "application/json");
  xmlHttp.setRequestHeader("Authorization", "Bearer " + getToken());
  xmlHttp.send(data);

  var issent = false;
  xmlHttp.onload = function () {
    if (issent)
      return;
    issent = true;
    var json = JSON.parse(xmlHttp.responseText);
    if (backfunc && json)
      backfunc( json);
  };
  xmlHttp.onerror = function () {
    trace("httpRequest.onerror--=" + xmlHttp.responseText);
    if (issent)
      return;
    issent = true;
    if (backfunc)
      backfunc( {code: 0, message: xmlHttp.responseText});
  };
  xmlHttp.ontimeout = function () {
    trace("httpRequest.ontimeout--=" + xmlHttp.responseText);
    if (issent)
      return;
    issent = true;
    if (backfunc)
      backfunc({code: 0, message: xmlHttp.responseText});
  };
}
